import { BrowserStorage } from 'my-web-core/storage';
import { createI18n } from 'vue-i18n';

import en from '@/locales/en.json';
import zhCn from '@/locales/zh-CN.json';
import LocaleName from '@/shared/constants/locale-name';
import StorageKey from '@/shared/constants/storage-key';

// Tries to load local saved locale.
let currentLocale = BrowserStorage.loadLocalData(StorageKey.locale);

// If there is No saved locale then reads it from current system locale.
if (currentLocale == null) {
  currentLocale = window.navigator.language;

  // Sets current locale based on system locale.
  if (currentLocale.toLowerCase().indexOf('zh') != -1) {
    currentLocale = LocaleName.zhCn;
  } else {
    currentLocale = LocaleName.en;
  }

  // Saves current locale to local storage for future use.
  BrowserStorage.saveLocalData(StorageKey.locale, currentLocale);
}

// Creates an instance of vue-i18n
const i18n = createI18n({
  legacy: false,
  locale: currentLocale,
  fallbackLocale: 'en',
  messages: {
    en,
    zhCn,
  },
});

export default i18n;
